package com.comp437.uno.view.login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.comp437.uno.model.ClientService;
import com.comp437.uno.model.Model;
import com.comp437.uno.model.ClientService.LocalBinder;
import com.example.comp437uno.R;

public class Settings extends Activity{
	Model model;
	EditText serverIP;
	EditText serverPort;
	Button bt_confirm,bt_cancel;
	String ip,port;
	Intent service;
	
	ClientService cs;
	boolean myBound=false;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		model=Model.getModel();
		serverIP= (EditText) findViewById(R.id.edittext_settings_serverip);
		serverPort = (EditText) findViewById(R.id.edittext_settings_portno);
		bt_confirm = (Button) findViewById(R.id.button_settings_confirm);
		bt_cancel = (Button) findViewById(R.id.button_settings_cancel);

		bt_confirm.setOnClickListener(new bt_ConfirmListener());
		bt_cancel.setOnClickListener(new bt_CancelListener());
		
		service = new Intent(Settings.this, ClientService.class);
		
		 bindService(service, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	class bt_ConfirmListener implements android.view.View.OnClickListener {

		public void onClick(View v) {
			// TODO Auto-generated method stub

			ip = serverIP.getText().toString();
			port = serverPort.getText().toString();
			model.setServer_ip(ip);
			model.setServerport(Integer.parseInt(port));
			 startService(service);
			Intent intent=new Intent();
			intent.setClass(Settings.this, Login.class);
			Settings.this.startActivity(intent);

		}
	}
	
	class bt_CancelListener implements android.view.View.OnClickListener {

		@SuppressLint("NewApi")
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Settings.this.onBackPressed();
		}
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) service;
            cs = binder.getService();
            model.setClientService(cs);
            myBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            myBound = false;
        }
    };
	
}
